package cn.wzc.crystal.platform.logic;

import java.util.Collection;
import java.util.Stack;

/**
 * 逻辑处理链
 */
public class LogicChain {

	private final Stack<Logic> logics;

	private LogicContext context;

	public LogicChain(Collection<Logic> logics) {
		this.logics = new Stack<>();
		this.logics.addAll(logics);
	}

	/**
	 * 继续执行逻辑处理链
	 *
	 * @param context 逻辑处理上下文
	 */
	public LogicContext doChain(LogicContext context) {
		this.context = context;
		this.doChainInternal();
		return this.context;
	}

	private void doChainInternal() {
		// 最后检查是否报错
		if (logics.empty()) {
			return;
		}

		// 弹出执行逻辑
		final LogicContext inContext = this.context;
		final Logic logic = logics.pop();
		this.context = logic.handle(inContext, this);
	}

	/**
	 * 获取包含的逻辑数量
	 *
	 * @return 逻辑数量
	 */
	public int getLogicCount() {
		return logics.size();
	}
}
